<?php
/*
 * @Date: 2022-09-23 13:54:49
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-07-16 16:00:11
 */

namespace Ldy\Models;

use Ldy\Model;
use tauthz\facade\Enforcer as Permission;
use Ldy\Models\SysAdminRole;
use Ldy\Models\SysRole;
use Ldy\Models\SysDepartment;

class SysAdmin extends Model{

    protected $title = "管理员";

    protected $hidden = ['password'];
    

    public static function getOptions(){
        $data = self::select();
        $res = [];
        foreach($data as $item) {
            $name = empty($item->nickname) ? $item->name:$item->nickname;
            if(empty($item->status)) $name = $name."(停用)";
            $res[$item->id] = $name;
        }

        return $res;
    }

    //全局定义查询条件
    // protected $globalScope = ['department_id'];

    public function adminRoles(){
        return $this->belongsToMany(SysRole::class, SysAdminRole::class, 'role_id', 'admin_id');
    }
    

    // public function scopeDepartment_id($query)
    // {
    //     $a = request()->get('department_id');
    //     print_r($a);
    //     // $rootName = config('plugin.ldy.admin.app.root_name');
    //     // $query->where('name','<>', $rootName);
    // }
    
    public function getRolesAttr($val){
        if(!is_array($val)) $val = empty($val) ? []:explode(',', $val);
        $res = [];
        foreach($val as $v) $res[]= intval($v);

		return $res; 
    }

    public function setPasswordAttr($val){
        return password_encode($val);
    }

    public function setAvatarAttr($val){
        
        if(empty($val)) return '';

        $app_url = env('APP_URL');
        if(is_array($val)) $val = $val[0];
		$res = str_replace($app_url, '', $val);
        return $res;
	}

    public function getAvatarAttr($val){
        $app_url = env('APP_URL');
		$res = $app_url. $val;
        return $val ? $res:$val;
	}

    // public function setModel(){
    //     $depId = request()->get('department_id');

	// 	$model = $this->alias('a')
    //     ->field('a.*,GROUP_CONCAT(r.role_id) AS roles')
    //     ->leftJoin('sys_admin_role r','r.admin_id=a.id')
    //     ->where('a.name','<>', root_name())
    //     ->group('a.id');

    //     if(!empty($depId) && $depId != 'ALL'){
    //         $depIds = SysDepartment::getSonDepIds($depId, false);
    //         $model = $model->where('a.department_id', 'in',$depIds);
    //     }
        
	// 	return $model;
	// }

    public static function onAfterInsert($model){
        $roles = request()->param('roles');

        $admin_id = $model->id;

        if(empty($admin_id)) return false;

        self::addAdminRoles($roles, $admin_id);
    }

    public static function onAfterUpdate($model){
        $roles = request()->param('roles');
        $admin_id = $model->id;

        if(empty($admin_id)) return false;

        //删除角色和管理员的关联关系
        $SysAdminRole = new SysAdminRole();
        $SysAdminRole->where('admin_id', $admin_id)->delete();
        //删除管理员所有角色
        Permission::deleteRolesForUser(strval($admin_id));

        if(empty($roles)) return false;

        self::addAdminRoles($roles, $admin_id);
    }

    protected static function addAdminRoles($roles,$admin_id){
        $sysAdminRole = new SysAdminRole();
		$data = [];
		foreach($roles as $role_id) {
            $data[] = ['admin_id' => $admin_id, 'role_id'=>$role_id];
            $roleName = casbin_role_field_prefix($role_id);
            Permission::addRoleForUser(strval($admin_id), $roleName);
        }
		$sysAdminRole->saveAll($data);
    }
}